home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 2002 November / SGI Freeware 2002 November - Disc 1.iso / dist / fw_emacs-lisp-intro.idb / usr / freeware / info / emacs-lisp-intro.info-9.z / emacs-lisp-intro.info-9
Text File  |  2002-07-08  |  46KB  |  1,116 lines

  1. This is emacs-lisp-intro.info, produced by makeinfo version 4.0b from
  2. emacs-lisp-intro.texi.
  3.  
  4. INFO-DIR-SECTION Emacs
  5. START-INFO-DIR-ENTRY
  6. * Emacs Lisp Intro: (eintr).
  7.               A simple introduction to Emacs Lisp programming.
  8. END-INFO-DIR-ENTRY
  9.  
  10.    This is an introduction to `Programming in Emacs Lisp', for people
  11. who are not programmers.
  12.  
  13.    Edition 2.04, 2001 Dec 17
  14.  
  15.    Copyright (C) 1990, '91, '92, '93, '94, '95, '97, 2001 Free Software
  16. Foundation, Inc.
  17.  
  18.    Permission is granted to copy, distribute and/or modify this document
  19. under the terms of the GNU Free Documentation License, Version 1.1 or
  20. any later version published by the Free Software Foundation; with the
  21. Invariant Section being the Preface, with the Front-Cover Texts being
  22. no Front-Cover Texts, and with the Back-Cover Texts being no Back-Cover
  23. Texts.  A copy of the license is included in the section entitled "GNU
  24. Free Documentation License".
  25.  
  26. 
  27. File: emacs-lisp-intro.info,  Node: sentence-end,  Next: re-search-forward,  Prev: Regexp Search,  Up: Regexp Search
  28.  
  29. The Regular Expression for `sentence-end'
  30. =========================================
  31.  
  32.    The symbol `sentence-end' is bound to the pattern that marks the end
  33. of a sentence.  What should this regular expression be?
  34.  
  35.    Clearly, a sentence may be ended by a period, a question mark, or an
  36. exclamation mark.  Indeed, only clauses that end with one of those three
  37. characters should be considered the end of a sentence.  This means that
  38. the pattern should include the character set:
  39.  
  40.      [.?!]
  41.  
  42.    However, we do not want `forward-sentence' merely to jump to a
  43. period, a question mark, or an exclamation mark, because such a
  44. character might be used in the middle of a sentence.  A period, for
  45. example, is used after abbreviations.  So other information is needed.
  46.  
  47.    According to convention, you type two spaces after every sentence,
  48. but only one space after a period, a question mark, or an exclamation
  49. mark in the body of a sentence.  So a period, a question mark, or an
  50. exclamation mark followed by two spaces is a good indicator of an end
  51. of sentence.  However, in a file, the two spaces may instead be a tab
  52. or the end of a line.  This means that the regular expression should
  53. include these three items as alternatives.
  54.  
  55.    This group of alternatives will look like this:
  56.  
  57.      \\($\\| \\|  \\)
  58.             ^   ^^
  59.            TAB  SPC
  60.  
  61. Here, `$' indicates the end of the line, and I have pointed out where
  62. the tab and two spaces are inserted in the expression.  Both are
  63. inserted by putting the actual characters into the expression.
  64.  
  65.    Two backslashes, `\\', are required before the parentheses and
  66. vertical bars: the first backslash quotes the following backslash in
  67. Emacs; and the second indicates that the following character, the
  68. parenthesis or the vertical bar, is special.
  69.  
  70.    Also, a sentence may be followed by one or more carriage returns,
  71. like this:
  72.  
  73.      [
  74.      ]*
  75.  
  76. Like tabs and spaces, a carriage return is inserted into a regular
  77. expression by inserting it literally.  The asterisk indicates that the
  78. <RET> is repeated zero or more times.
  79.  
  80.    But a sentence end does not consist only of a period, a question
  81. mark or an exclamation mark followed by appropriate space: a closing
  82. quotation mark or a closing brace of some kind may precede the space.
  83. Indeed more than one such mark or brace may precede the space.  These
  84. require a expression that looks like this:
  85.  
  86.      []\"')}]*
  87.  
  88.    In this expression, the first `]' is the first character in the
  89. expression; the second character is `"', which is preceded by a `\' to
  90. tell Emacs the `"' is _not_ special.  The last three characters are
  91. `'', `)', and `}'.
  92.  
  93.    All this suggests what the regular expression pattern for matching
  94. the end of a sentence should be; and, indeed, if we evaluate
  95. `sentence-end' we find that it returns the following value:
  96.  
  97.      sentence-end
  98.           => "[.?!][]\"')}]*\\($\\|     \\|  \\)[
  99.      ]*"
  100.  
  101. 
  102. File: emacs-lisp-intro.info,  Node: re-search-forward,  Next: forward-sentence,  Prev: sentence-end,  Up: Regexp Search
  103.  
  104. The `re-search-forward' Function
  105. ================================
  106.  
  107.    The `re-search-forward' function is very like the `search-forward'
  108. function.  (*Note The `search-forward' Function: search-forward.)
  109.  
  110.    `re-search-forward' searches for a regular expression.  If the
  111. search is successful, it leaves point immediately after the last
  112. character in the target.  If the search is backwards, it leaves point
  113. just before the first character in the target.  You may tell
  114. `re-search-forward' to return `t' for true.  (Moving point is therefore
  115. a `side effect'.)
  116.  
  117.    Like `search-forward', the `re-search-forward' function takes four
  118. arguments:
  119.  
  120.   1. The first argument is the regular expression that the function
  121.      searches for.  The regular expression will be a string between
  122.      quotations marks.
  123.  
  124.   2. The optional second argument limits how far the function will
  125.      search; it is a bound, which is specified as a position in the
  126.      buffer.
  127.  
  128.   3. The optional third argument specifies how the function responds to
  129.      failure: `nil' as the third argument causes the function to signal
  130.      an error (and print a message) when the search fails; any other
  131.      value causes it to return `nil' if the search fails and `t' if the
  132.      search succeeds.
  133.  
  134.   4. The optional fourth argument is the repeat count.  A negative
  135.      repeat count causes `re-search-forward' to search backwards.
  136.  
  137.    The template for `re-search-forward' looks like this:
  138.  
  139.      (re-search-forward "REGULAR-EXPRESSION"
  140.                      LIMIT-OF-SEARCH
  141.                      WHAT-TO-DO-IF-SEARCH-FAILS
  142.                      REPEAT-COUNT)
  143.  
  144.    The second, third, and fourth arguments are optional.  However, if
  145. you want to pass a value to either or both of the last two arguments,
  146. you must also pass a value to all the preceding arguments.  Otherwise,
  147. the Lisp interpreter will mistake which argument you are passing the
  148. value to.
  149.  
  150.    In the `forward-sentence' function, the regular expression will be
  151. the value of the variable `sentence-end', namely:
  152.  
  153.      "[.?!][]\"')}]*\\($\\|  \\|  \\)[
  154.      ]*"
  155.  
  156. The limit of the search will be the end of the paragraph (since a
  157. sentence cannot go beyond a paragraph).  If the search fails, the
  158. function will return `nil'; and the repeat count will be provided by
  159. the argument to the `forward-sentence' function.
  160.  
  161. 
  162. File: emacs-lisp-intro.info,  Node: forward-sentence,  Next: forward-paragraph,  Prev: re-search-forward,  Up: Regexp Search
  163.  
  164. `forward-sentence'
  165. ==================
  166.  
  167.    The command to move the cursor forward a sentence is a
  168. straightforward illustration of how to use regular expression searches
  169. in Emacs Lisp.  Indeed, the function looks longer and more complicated
  170. than it is; this is because the function is designed to go backwards as
  171. well as forwards; and, optionally, over more than one sentence.  The
  172. function is usually bound to the key command `M-e'.
  173.  
  174. * Menu:
  175.  
  176. * Complete forward-sentence::
  177. * fwd-sentence while loops::    Two `while' loops.
  178. * fwd-sentence re-search::      A regular expression search.
  179.  
  180. 
  181. File: emacs-lisp-intro.info,  Node: Complete forward-sentence,  Next: fwd-sentence while loops,  Prev: forward-sentence,  Up: forward-sentence
  182.  
  183. Complete `forward-sentence' function definition
  184. -----------------------------------------------
  185.  
  186.    Here is the code for `forward-sentence':
  187.  
  188.      (defun forward-sentence (&optional arg)
  189.        "Move forward to next sentence-end.  With argument, repeat.
  190.      With negative argument, move backward repeatedly to sentence-beginning.
  191.      Sentence ends are identified by the value of sentence-end
  192.      treated as a regular expression.  Also, every paragraph boundary
  193.      terminates sentences as well."
  194.        (interactive "p")
  195.        (or arg (setq arg 1))
  196.        (while (< arg 0)
  197.          (let ((par-beg
  198.                 (save-excursion (start-of-paragraph-text) (point))))
  199.            (if (re-search-backward
  200.                 (concat sentence-end "[^ \t\n]") par-beg t)
  201.                (goto-char (1- (match-end 0)))
  202.              (goto-char par-beg)))
  203.          (setq arg (1+ arg)))
  204.        (while (> arg 0)
  205.          (let ((par-end
  206.                 (save-excursion (end-of-paragraph-text) (point))))
  207.            (if (re-search-forward sentence-end par-end t)
  208.                (skip-chars-backward " \t\n")
  209.              (goto-char par-end)))
  210.          (setq arg (1- arg))))
  211.  
  212.    The function looks long at first sight and it is best to look at its
  213. skeleton first, and then its muscle.  The way to see the skeleton is to
  214. look at the expressions that start in the left-most columns:
  215.  
  216.      (defun forward-sentence (&optional arg)
  217.        "DOCUMENTATION..."
  218.        (interactive "p")
  219.        (or arg (setq arg 1))
  220.        (while (< arg 0)
  221.          BODY-OF-WHILE-LOOP
  222.        (while (> arg 0)
  223.          BODY-OF-WHILE-LOOP
  224.  
  225.    This looks much simpler!  The function definition consists of
  226. documentation, an `interactive' expression, an `or' expression, and
  227. `while' loops.
  228.  
  229.    Let's look at each of these parts in turn.
  230.  
  231.    We note that the documentation is thorough and understandable.
  232.  
  233.    The function has an `interactive "p"' declaration.  This means that
  234. the processed prefix argument, if any, is passed to the function as its
  235. argument.  (This will be a number.)  If the function is not passed an
  236. argument (it is optional) then the argument `arg' will be bound to 1.
  237. When `forward-sentence' is called non-interactively without an
  238. argument, `arg' is bound to `nil'.
  239.  
  240.    The `or' expression handles the prefix argument.  What it does is
  241. either leave the value of `arg' as it is, but only if `arg' is bound to
  242. a value; or it sets the value of `arg' to 1, in the case when `arg' is
  243. bound to `nil'.
  244.  
  245. 
  246. File: emacs-lisp-intro.info,  Node: fwd-sentence while loops,  Next: fwd-sentence re-search,  Prev: Complete forward-sentence,  Up: forward-sentence
  247.  
  248. The `while' loops
  249. -----------------
  250.  
  251.    Two `while' loops follow the `or' expression.  The first `while' has
  252. a true-or-false-test that tests true if the prefix argument for
  253. `forward-sentence' is a negative number.  This is for going backwards.
  254. The body of this loop is similar to the body of the second `while'
  255. clause, but it is not exactly the same.  We will skip this `while' loop
  256. and concentrate on the second `while' loop.
  257.  
  258.    The second `while' loop is for moving point forward.  Its skeleton
  259. looks like this:
  260.  
  261.      (while (> arg 0)            ; true-or-false-test
  262.        (let VARLIST
  263.          (if (TRUE-OR-FALSE-TEST)
  264.              THEN-PART
  265.            ELSE-PART
  266.        (setq arg (1- arg))))     ; `while' loop decrementer
  267.  
  268.    The `while' loop is of the decrementing kind.  (*Note A Loop with a
  269. Decrementing Counter: Decrementing Loop.)  It has a true-or-false-test
  270. that tests true so long as the counter (in this case, the variable
  271. `arg') is greater than zero; and it has a decrementer that subtracts 1
  272. from the value of the counter every time the loop repeats.
  273.  
  274.    If no prefix argument is given to `forward-sentence', which is the
  275. most common way the command is used, this `while' loop will run once,
  276. since the value of `arg' will be 1.
  277.  
  278.    The body of the `while' loop consists of a `let' expression, which
  279. creates and binds a local variable, and has, as its body, an `if'
  280. expression.
  281.  
  282.    The body of the `while' loop looks like this:
  283.  
  284.      (let ((par-end
  285.             (save-excursion (end-of-paragraph-text) (point))))
  286.        (if (re-search-forward sentence-end par-end t)
  287.            (skip-chars-backward " \t\n")
  288.          (goto-char par-end)))
  289.  
  290.    The `let' expression creates and binds the local variable `par-end'.
  291. As we shall see, this local variable is designed to provide a bound or
  292. limit to the regular expression search.  If the search fails to find a
  293. proper sentence ending in the paragraph, it will stop on reaching the
  294. end of the paragraph.
  295.  
  296.    But first, let us examine how `par-end' is bound to the value of the
  297. end of the paragraph.  What happens is that the `let' sets the value of
  298. `par-end' to the value returned when the Lisp interpreter evaluates the
  299. expression
  300.  
  301.      (save-excursion (end-of-paragraph-text) (point))
  302.  
  303. In this expression, `(end-of-paragraph-text)' moves point to the end of
  304. the paragraph, `(point)' returns the value of point, and then
  305. `save-excursion' restores point to its original position.  Thus, the
  306. `let' binds `par-end' to the value returned by the `save-excursion'
  307. expression, which is the position of the end of the paragraph.  (The
  308. `(end-of-paragraph-text)' function uses `forward-paragraph', which we
  309. will discuss shortly.)
  310.  
  311.    Emacs next evaluates the body of the `let', which is an `if'
  312. expression that looks like this:
  313.  
  314.      (if (re-search-forward sentence-end par-end t) ; if-part
  315.          (skip-chars-backward " \t\n")              ; then-part
  316.        (goto-char par-end)))                        ; else-part
  317.  
  318.    The `if' tests whether its first argument is true and if so,
  319. evaluates its then-part; otherwise, the Emacs Lisp interpreter
  320. evaluates the else-part.  The true-or-false-test of the `if' expression
  321. is the regular expression search.
  322.  
  323.    It may seem odd to have what looks like the `real work' of the
  324. `forward-sentence' function buried here, but this is a common way this
  325. kind of operation is carried out in Lisp.
  326.  
  327. 
  328. File: emacs-lisp-intro.info,  Node: fwd-sentence re-search,  Prev: fwd-sentence while loops,  Up: forward-sentence
  329.  
  330. The regular expression search
  331. -----------------------------
  332.  
  333.    The `re-search-forward' function searches for the end of the
  334. sentence, that is, for the pattern defined by the `sentence-end'
  335. regular expression.  If the pattern is found--if the end of the
  336. sentence is found--then the `re-search-forward' function does two
  337. things:
  338.  
  339.   1. The `re-search-forward' function carries out a side effect, which
  340.      is to move point to the end of the occurrence found.
  341.  
  342.   2. The `re-search-forward' function returns a value of true.  This is
  343.      the value received by the `if', and means that the search was
  344.      successful.
  345.  
  346. The side effect, the movement of point, is completed before the `if'
  347. function is handed the value returned by the successful conclusion of
  348. the search.
  349.  
  350.    When the `if' function receives the value of true from a successful
  351. call to `re-search-forward', the `if' evaluates the then-part, which is
  352. the expression `(skip-chars-backward " \t\n")'.  This expression moves
  353. backwards over any blank spaces, tabs or carriage returns until a
  354. printed character is found and then leaves point after the character.
  355. Since point has already been moved to the end of the pattern that marks
  356. the end of the sentence, this action leaves point right after the
  357. closing printed character of the sentence, which is usually a period.
  358.  
  359.    On the other hand, if the `re-search-forward' function fails to find
  360. a pattern marking the end of the sentence, the function returns false.
  361. The false then causes the `if' to evaluate its third argument, which is
  362. `(goto-char par-end)':  it moves point to the end of the paragraph.
  363.  
  364.    Regular expression searches are exceptionally useful and the pattern
  365. illustrated by `re-search-forward', in which the search is the test of
  366. an `if' expression, is handy.  You will see or write code incorporating
  367. this pattern often.
  368.  
  369. 
  370. File: emacs-lisp-intro.info,  Node: forward-paragraph,  Next: etags,  Prev: forward-sentence,  Up: Regexp Search
  371.  
  372. `forward-paragraph': a Goldmine of Functions
  373. ============================================
  374.  
  375.    The `forward-paragraph' function moves point forward to the end of
  376. the paragraph.  It is usually bound to `M-}' and makes use of a number
  377. of functions that are important in themselves, including `let*',
  378. `match-beginning', and `looking-at'.
  379.  
  380.    The function definition for `forward-paragraph' is considerably
  381. longer than the function definition for `forward-sentence' because it
  382. works with a paragraph, each line of which may begin with a fill prefix.
  383.  
  384.    A fill prefix consists of a string of characters that are repeated at
  385. the beginning of each line.  For example, in Lisp code, it is a
  386. convention to start each line of a paragraph-long comment with `;;; '.
  387. In Text mode, four blank spaces make up another common fill prefix,
  388. creating an indented paragraph.  (*Note Fill Prefix: (emacs)Fill
  389. Prefix, for more information about fill prefixes.)
  390.  
  391.    The existence of a fill prefix means that in addition to being able
  392. to find the end of a paragraph whose lines begin on the left-most
  393. column, the `forward-paragraph' function must be able to find the end
  394. of a paragraph when all or many of the lines in the buffer begin with
  395. the fill prefix.
  396.  
  397.    Moreover, it is sometimes practical to ignore a fill prefix that
  398. exists, especially when blank lines separate paragraphs.  This is an
  399. added complication.
  400.  
  401. * Menu:
  402.  
  403. * forward-paragraph in brief::  Key parts of the function definition.
  404. * fwd-para let::                The `let*' expression.
  405. * fwd-para while::              The forward motion `while' loop.
  406. * fwd-para between paragraphs::  Movement between paragraphs.
  407. * fwd-para within paragraph::   Movement within paragraphs.
  408. * fwd-para no fill prefix::     When there is no fill prefix.
  409. * fwd-para with fill prefix::   When there is a fill prefix.
  410. * fwd-para summary::            Summary of `forward-paragraph' code.
  411.  
  412. 
  413. File: emacs-lisp-intro.info,  Node: forward-paragraph in brief,  Next: fwd-para let,  Prev: forward-paragraph,  Up: forward-paragraph
  414.  
  415. Shortened `forward-paragraph' function definition
  416. -------------------------------------------------
  417.  
  418.    Rather than print all of the `forward-paragraph' function, we will
  419. only print parts of it.  Read without preparation, the function can be
  420. daunting!
  421.  
  422.    In outline, the function looks like this:
  423.  
  424.      (defun forward-paragraph (&optional arg)
  425.        "DOCUMENTATION..."
  426.        (interactive "p")
  427.        (or arg (setq arg 1))
  428.        (let*
  429.            VARLIST
  430.          (while (< arg 0)        ; backward-moving-code
  431.            ...
  432.            (setq arg (1+ arg)))
  433.          (while (> arg 0)        ; forward-moving-code
  434.            ...
  435.            (setq arg (1- arg)))))
  436.  
  437.    The first parts of the function are routine: the function's argument
  438. list consists of one optional argument.  Documentation follows.
  439.  
  440.    The lower case `p' in the `interactive' declaration means that the
  441. processed prefix argument, if any, is passed to the function.  This
  442. will be a number, and is the repeat count of how many paragraphs point
  443. will move.  The `or' expression in the next line handles the common
  444. case when no argument is passed to the function, which occurs if the
  445. function is called from other code rather than interactively.  This
  446. case was described earlier.  (*Note The `forward-sentence' function:
  447. forward-sentence.)  Now we reach the end of the familiar part of this
  448. function.
  449.  
  450. 
  451. File: emacs-lisp-intro.info,  Node: fwd-para let,  Next: fwd-para while,  Prev: forward-paragraph in brief,  Up: forward-paragraph
  452.  
  453. The `let*' expression
  454. ---------------------
  455.  
  456.    The next line of the `forward-paragraph' function begins a `let*'
  457. expression.  This is a different kind of expression than we have seen
  458. so far.  The symbol is `let*' not `let'.
  459.  
  460.    The `let*' special form is like `let' except that Emacs sets each
  461. variable in sequence, one after another, and variables in the latter
  462. part of the varlist can make use of the values to which Emacs set
  463. variables in the earlier part of the varlist.
  464.  
  465.    In the `let*' expression in this function, Emacs binds two
  466. variables: `fill-prefix-regexp' and `paragraph-separate'.  The value to
  467. which `paragraph-separate' is bound depends on the value of
  468. `fill-prefix-regexp'.
  469.  
  470.    Let's look at each in turn.  The symbol `fill-prefix-regexp' is set
  471. to the value returned by evaluating the following list:
  472.  
  473.      (and fill-prefix
  474.           (not (equal fill-prefix ""))
  475.           (not paragraph-ignore-fill-prefix)
  476.           (regexp-quote fill-prefix))
  477.  
  478. This is an expression whose first element is the `and' special form.
  479.  
  480.    As we learned earlier (*note The `kill-new' function: kill-new
  481. function.), the `and' special form evaluates each of its arguments
  482. until one of the arguments returns a value of `nil', in which case the
  483. `and' expression returns `nil'; however, if none of the arguments
  484. returns a value of `nil', the value resulting from evaluating the last
  485. argument is returned.  (Since such a value is not `nil', it is
  486. considered true in Lisp.)  In other words, an `and' expression returns
  487. a true value only if all its arguments are true.
  488.  
  489.    In this case, the variable `fill-prefix-regexp' is bound to a
  490. non-`nil' value only if the following four expressions produce a true
  491. (i.e., a non-`nil') value when they are evaluated; otherwise,
  492. `fill-prefix-regexp' is bound to `nil'.
  493.  
  494. `fill-prefix'
  495.      When this variable is evaluated, the value of the fill prefix, if
  496.      any, is returned.  If there is no fill prefix, this variable
  497.      returns `nil'.
  498.  
  499. `(not (equal fill-prefix "")'
  500.      This expression checks whether an existing fill prefix is an empty
  501.      string, that is, a string with no characters in it.  An empty
  502.      string is not a useful fill prefix.
  503.  
  504. `(not paragraph-ignore-fill-prefix)'
  505.      This expression returns `nil' if the variable
  506.      `paragraph-ignore-fill-prefix' has been turned on by being set to a
  507.      true value such as `t'.
  508.  
  509. `(regexp-quote fill-prefix)'
  510.      This is the last argument to the `and' special form.  If all the
  511.      arguments to the `and' are true, the value resulting from
  512.      evaluating this expression will be returned by the `and' expression
  513.      and bound to the variable `fill-prefix-regexp',
  514.  
  515. The result of evaluating this `and' expression successfully is that
  516. `fill-prefix-regexp' will be bound to the value of `fill-prefix' as
  517. modified by the `regexp-quote' function.  What `regexp-quote' does is
  518. read a string and return a regular expression that will exactly match
  519. the string and match nothing else.  This means that
  520. `fill-prefix-regexp' will be set to a value that will exactly match the
  521. fill prefix if the fill prefix exists.  Otherwise, the variable will be
  522. set to `nil'.
  523.  
  524.    The second local variable in the `let*' expression is
  525. `paragraph-separate'.  It is bound to the value returned by evaluating
  526. the expression:
  527.  
  528.      (if fill-prefix-regexp
  529.          (concat paragraph-separate
  530.                  "\\|^" fill-prefix-regexp "[ \t]*$")
  531.        paragraph-separate)))
  532.  
  533.    This expression shows why `let*' rather than `let' was used.  The
  534. true-or-false-test for the `if' depends on whether the variable
  535. `fill-prefix-regexp' evaluates to `nil' or some other value.
  536.  
  537.    If `fill-prefix-regexp' does not have a value, Emacs evaluates the
  538. else-part of the `if' expression and binds `paragraph-separate' to its
  539. local value.  (`paragraph-separate' is a regular expression that
  540. matches what separates paragraphs.)
  541.  
  542.    But if `fill-prefix-regexp' does have a value, Emacs evaluates the
  543. then-part of the `if' expression and binds `paragraph-separate' to a
  544. regular expression that includes the `fill-prefix-regexp' as part of
  545. the pattern.
  546.  
  547.    Specifically, `paragraph-separate' is set to the original value of
  548. the paragraph separate regular expression concatenated with an
  549. alternative expression that consists of the `fill-prefix-regexp'
  550. followed by a blank line.  The `^' indicates that the
  551. `fill-prefix-regexp' must begin a line, and the optional whitespace to
  552. the end of the line is defined by `"[ \t]*$"'.)  The `\\|' defines this
  553. portion of the regexp as an alternative to `paragraph-separate'.
  554.  
  555.    Now we get into the body of the `let*'.  The first part of the body
  556. of the `let*' deals with the case when the function is given a negative
  557. argument and is therefore moving backwards.  We will skip this section.
  558.  
  559. 
  560. File: emacs-lisp-intro.info,  Node: fwd-para while,  Next: fwd-para between paragraphs,  Prev: fwd-para let,  Up: forward-paragraph
  561.  
  562. The forward motion `while' loop
  563. -------------------------------
  564.  
  565.    The second part of the body of the `let*' deals with forward motion.
  566. It is a `while' loop that repeats itself so long as the value of `arg'
  567. is greater than zero.  In the most common use of the function, the
  568. value of the argument is 1, so the body of the `while' loop is
  569. evaluated exactly once, and the cursor moves forward one paragraph.
  570.  
  571.    This part handles three situations: when point is between paragraphs,
  572. when point is within a paragraph and there is a fill prefix, and when
  573. point is within a paragraph and there is no fill prefix.
  574.  
  575.    The `while' loop looks like this:
  576.  
  577.      (while (> arg 0)
  578.        (beginning-of-line)
  579.      
  580.        ;; between paragraphs
  581.        (while (prog1 (and (not (eobp))
  582.                           (looking-at paragraph-separate))
  583.                 (forward-line 1)))
  584.      
  585.        ;; within paragraphs, with a fill prefix
  586.        (if fill-prefix-regexp
  587.            ;; There is a fill prefix; it overrides paragraph-start.
  588.            (while (and (not (eobp))
  589.                        (not (looking-at paragraph-separate))
  590.                        (looking-at fill-prefix-regexp))
  591.              (forward-line 1))
  592.      
  593.          ;; within paragraphs, no fill prefix
  594.          (if (re-search-forward paragraph-start nil t)
  595.              (goto-char (match-beginning 0))
  596.            (goto-char (point-max))))
  597.      
  598.        (setq arg (1- arg)))
  599.  
  600.    We can see immediately that this is a decrementing counter `while'
  601. loop, using the expression `(setq arg (1- arg))' as the decrementer.
  602.  
  603.    The body of the loop consists of three expressions:
  604.  
  605.      ;; between paragraphs
  606.      (beginning-of-line)
  607.      (while
  608.          BODY-OF-WHILE)
  609.      
  610.      ;; within paragraphs, with fill prefix
  611.      (if TRUE-OR-FALSE-TEST
  612.          THEN-PART
  613.      
  614.      ;; within paragraphs, no fill prefix
  615.        ELSE-PART
  616.  
  617. When the Emacs Lisp interpreter evaluates the body of the `while' loop,
  618. the first thing it does is evaluate the `(beginning-of-line)'
  619. expression and move point to the beginning of the line.  Then there is
  620. an inner `while' loop.  This `while' loop is designed to move the
  621. cursor out of the blank space between paragraphs, if it should happen
  622. to be there.  Finally, there is an `if' expression that actually moves
  623. point to the end of the paragraph.
  624.  
  625. 
  626. File: emacs-lisp-intro.info,  Node: fwd-para between paragraphs,  Next: fwd-para within paragraph,  Prev: fwd-para while,  Up: forward-paragraph
  627.  
  628. Between paragraphs
  629. ------------------
  630.  
  631.    First, let us look at the inner `while' loop.  This loop handles the
  632. case when point is between paragraphs; it uses three functions that are
  633. new to us: `prog1', `eobp' and `looking-at'.
  634.  
  635.    * `prog1' is similar to the `progn' special form, except that
  636.      `prog1' evaluates its arguments in sequence and then returns the
  637.      value of its first argument as the value of the whole expression.
  638.      (`progn' returns the value of its last argument as the value of
  639.      the expression.) The second and subsequent arguments to `prog1'
  640.      are evaluated only for their side effects.
  641.  
  642.    * `eobp' is an abbreviation of `End Of Buffer P' and is a function
  643.      that returns true if point is at the end of the buffer.
  644.  
  645.    * `looking-at' is a function that returns true if the text following
  646.      point matches the regular expression passed `looking-at' as its
  647.      argument.
  648.  
  649.    The `while' loop we are studying looks like this:
  650.  
  651.      (while (prog1 (and (not (eobp))
  652.                         (looking-at paragraph-separate))
  653.                    (forward-line 1)))
  654.  
  655. This is a `while' loop with no body!  The true-or-false-test of the
  656. loop is the expression:
  657.  
  658.      (prog1 (and (not (eobp))
  659.                  (looking-at paragraph-separate))
  660.             (forward-line 1))
  661.  
  662. The first argument to the `prog1' is the `and' expression.  It has
  663. within in it a test of whether point is at the end of the buffer and
  664. also a test of whether the pattern following point matches the regular
  665. expression for separating paragraphs.
  666.  
  667.    If the cursor is not at the end of the buffer and if the characters
  668. following the cursor mark the separation between two paragraphs, then
  669. the `and' expression is true.  After evaluating the `and' expression,
  670. the Lisp interpreter evaluates the second argument to `prog1', which is
  671. `forward-line'.  This moves point forward one line.  The value returned
  672. by the `prog1' however, is the value of its first argument, so the
  673. `while' loop continues so long as point is not at the end of the buffer
  674. and is between paragraphs.  When, finally, point is moved to a
  675. paragraph, the `and' expression tests false.  Note however, that the
  676. `forward-line' command is carried out anyhow.  This means that when
  677. point is moved from between paragraphs to a paragraph, it is left at
  678. the beginning of the second line of the paragraph.
  679.  
  680. 
  681. File: emacs-lisp-intro.info,  Node: fwd-para within paragraph,  Next: fwd-para no fill prefix,  Prev: fwd-para between paragraphs,  Up: forward-paragraph
  682.  
  683. Within paragraphs
  684. -----------------
  685.  
  686.    The next expression in the outer `while' loop is an `if' expression.
  687. The Lisp interpreter evaluates the then-part of the `if' when the
  688. `fill-prefix-regexp' variable has a value other than `nil', and it
  689. evaluates the else-part when the value of `if fill-prefix-regexp' is
  690. `nil', that is, when there is no fill prefix.
  691.  
  692. 
  693. File: emacs-lisp-intro.info,  Node: fwd-para no fill prefix,  Next: fwd-para with fill prefix,  Prev: fwd-para within paragraph,  Up: forward-paragraph
  694.  
  695. No fill prefix
  696. --------------
  697.  
  698.    It is simplest to look at the code for the case when there is no fill
  699. prefix first.  This code consists of yet another inner `if' expression,
  700. and reads as follows:
  701.  
  702.      (if (re-search-forward paragraph-start nil t)
  703.          (goto-char (match-beginning 0))
  704.        (goto-char (point-max)))
  705.  
  706. This expression actually does the work that most people think of as the
  707. primary purpose of the `forward-paragraph' command: it causes a regular
  708. expression search to occur that searches forward to the start of the
  709. next paragraph and if it is found, moves point there; but if the start
  710. of another paragraph if not found, it moves point to the end of the
  711. accessible region of the buffer.
  712.  
  713.    The only unfamiliar part of this is the use of `match-beginning'.
  714. This is another function that is new to us.  The `match-beginning'
  715. function returns a number specifying the location of the start of the
  716. text that was matched by the last regular expression search.
  717.  
  718.    The `match-beginning' function is used here because of a
  719. characteristic of a forward search: a successful forward search,
  720. regardless of whether it is a plain search or a regular expression
  721. search, will move point to the end of the text that is found.  In this
  722. case, a successful search will move point to the end of the pattern for
  723. `paragraph-start', which will be the beginning of the next paragraph
  724. rather than the end of the current one.
  725.  
  726.    However, we want to put point at the end of the current paragraph,
  727. not at the beginning of the next one.  The two positions may be
  728. different, because there may be several blank lines between paragraphs.
  729.  
  730.    When given an argument of 0, `match-beginning' returns the position
  731. that is the start of the text that the most recent regular expression
  732. search matched.  In this case, the most recent regular expression
  733. search is the one looking for `paragraph-start', so `match-beginning'
  734. returns the beginning position of the pattern, rather than the end of
  735. the pattern.  The beginning position is the end of the paragraph.
  736.  
  737.    (Incidentally, when passed a positive number as an argument, the
  738. `match-beginning' function will place point at that parenthesized
  739. expression in the last regular expression.  It is a useful function.)
  740.  
  741. 
  742. File: emacs-lisp-intro.info,  Node: fwd-para with fill prefix,  Next: fwd-para summary,  Prev: fwd-para no fill prefix,  Up: forward-paragraph
  743.  
  744. With a fill prefix
  745. ------------------
  746.  
  747.    The inner `if' expression just discussed is the else-part of an
  748. enclosing `if' expression which tests whether there is a fill prefix.
  749. If there is a fill prefix, the then-part of this `if' is evaluated.  It
  750. looks like this:
  751.  
  752.      (while (and (not (eobp))
  753.                  (not (looking-at paragraph-separate))
  754.                  (looking-at fill-prefix-regexp))
  755.        (forward-line 1))
  756.  
  757. What this expression does is move point forward line by line so long as
  758. three conditions are true:
  759.  
  760.   1. Point is not at the end of the buffer.
  761.  
  762.   2. The text following point does not separate paragraphs.
  763.  
  764.   3. The pattern following point is the fill prefix regular expression.
  765.  
  766.    The last condition may be puzzling, until you remember that point was
  767. moved to the beginning of the line early in the `forward-paragraph'
  768. function.  This means that if the text has a fill prefix, the
  769. `looking-at' function will see it.
  770.  
  771. 
  772. File: emacs-lisp-intro.info,  Node: fwd-para summary,  Prev: fwd-para with fill prefix,  Up: forward-paragraph
  773.  
  774. Summary
  775. -------
  776.  
  777.    In summary, when moving forward, the `forward-paragraph' function
  778. does the following:
  779.  
  780.    * Move point to the beginning of the line.
  781.  
  782.    * Skip over lines between paragraphs.
  783.  
  784.    * Check whether there is a fill prefix, and if there is:
  785.  
  786.         -- Go forward line by line so long as the line is not a
  787.           paragraph separating line.
  788.  
  789.    * But if there is no fill prefix,
  790.  
  791.         -- Search for the next paragraph start pattern.
  792.  
  793.         -- Go to the beginning of the paragraph start pattern, which
  794.           will be the end of the previous paragraph.
  795.  
  796.         -- Or else go to the end of the accessible portion of the
  797.           buffer.
  798.  
  799.    For review, here is the code we have just been discussing, formatted
  800. for clarity:
  801.  
  802.      (interactive "p")
  803.      (or arg (setq arg 1))
  804.      (let* (
  805.             (fill-prefix-regexp
  806.              (and fill-prefix (not (equal fill-prefix ""))
  807.                   (not paragraph-ignore-fill-prefix)
  808.                   (regexp-quote fill-prefix)))
  809.      
  810.             (paragraph-separate
  811.              (if fill-prefix-regexp
  812.                  (concat paragraph-separate
  813.                          "\\|^"
  814.                          fill-prefix-regexp
  815.                          "[ \t]*$")
  816.                paragraph-separate)))
  817.      
  818.        OMITTED-BACKWARD-MOVING-CODE ...
  819.      
  820.        (while (> arg 0)                ; forward-moving-code
  821.          (beginning-of-line)
  822.      
  823.          (while (prog1 (and (not (eobp))
  824.                             (looking-at paragraph-separate))
  825.                   (forward-line 1)))
  826.      
  827.          (if fill-prefix-regexp
  828.              (while (and (not (eobp))  ; then-part
  829.                          (not (looking-at paragraph-separate))
  830.                          (looking-at fill-prefix-regexp))
  831.                (forward-line 1))
  832.                                        ; else-part: the inner-if
  833.            (if (re-search-forward paragraph-start nil t)
  834.                (goto-char (match-beginning 0))
  835.              (goto-char (point-max))))
  836.      
  837.          (setq arg (1- arg)))))        ; decrementer
  838.  
  839.    The full definition for the `forward-paragraph' function not only
  840. includes this code for going forwards, but also code for going
  841. backwards.
  842.  
  843.    If you are reading this inside of GNU Emacs and you want to see the
  844. whole function, you can type `C-h f' (`describe-function') and the name
  845. of the function.  This gives you the function documentation and the
  846. name of the library containing the function's source.  Place point over
  847. the name of the library and press the RET key; you will be taken
  848. directly to the source.  (Be sure to install your sources!  Without
  849. them, you are like a person who tries to drive a car with his eyes
  850. shut!)
  851.  
  852.    Or - a good habit to get into - you can type `M-.' (`find-tag') and
  853. the name of the function when prompted for it.  This will take you
  854. directly to the source.  If the `find-tag' function first asks you for
  855. the name of a `TAGS' table, give it the name of the `TAGS' file such as
  856. `/usr/local/share/emacs/21.0.100/lisp/TAGS'.  (The exact path to your
  857. `TAGS' file depends on how your copy of Emacs was installed.)
  858.  
  859.    You can also create your own `TAGS' file for directories that lack
  860. one.  *Note Create Your Own `TAGS' File: etags.
  861.  
  862. 
  863. File: emacs-lisp-intro.info,  Node: etags,  Next: Regexp Review,  Prev: forward-paragraph,  Up: Regexp Search
  864.  
  865. Create Your Own `TAGS' File
  866. ===========================
  867.  
  868.    The `M-.' (`find-tag') command takes you directly to the source for
  869. a function, variable, node, or other source.  The function depends on
  870. tags tables to tell it where to go.
  871.  
  872.    You often need to build and install tags tables yourself.  They are
  873. not built automatically.  A tags table is called a `TAGS' file; the
  874. name is in upper case letters.
  875.  
  876.    You can create a `TAGS' file by calling the `etags' program that
  877. comes as a part of the Emacs distribution.  Usually, `etags' is
  878. compiled and installed when Emacs is built.  (`etags' is not an Emacs
  879. Lisp function or a part of Emacs; it is a C program.)
  880.  
  881.    To create a `TAGS' file, first switch to the directory in which you
  882. want to create the file.  In Emacs you can do this with the `M-x cd'
  883. command, or by visiting a file in the directory, or by listing the
  884. directory with `C-x d' (`dired').  Then run the compile command, with
  885. `etags *.el' as the command to execute
  886.  
  887.      M-x compile RET etags *.el RET
  888.  
  889. to create a `TAGS' file.
  890.  
  891.    For example, if you have a large number of files in your `~/emacs'
  892. directory, as I do--I have 137 `.el' files in it, of which I load
  893. 12--you can create a `TAGS' file for the Emacs Lisp files in that
  894. directory.
  895.  
  896.    The `etags' program takes all the usual shell `wildcards'.  For
  897. example, if you have two directories for which you want a single `TAGS
  898. file', type `etags *.el ../elisp/*.el', where `../elisp/' is the second
  899. directory:
  900.  
  901.      M-x compile RET etags *.el ../elisp/*.el RET
  902.  
  903.    Type
  904.  
  905.      M-x compile RET etags --help RET
  906.  
  907. to see a list of the options accepted by `etags' as well as a list of
  908. supported languages.
  909.  
  910.    The `etags' program handles more than 20 languages, including Emacs
  911. Lisp, Common Lisp, Scheme, C, C++, Ada, Fortran, Java, LaTeX, Pascal,
  912. Perl, Python, Texinfo, makefiles, and most assemblers.  The program has
  913. no switches for specifying the language; it recognizes the language in
  914. an input file according to its file name and contents.
  915.  
  916.    `etags' is very helpful when you are writing code yourself and want
  917. to refer back to functions you have already written.  Just run `etags'
  918. again at intervals as you write new functions, so they become part of
  919. the `TAGS' file.
  920.  
  921.    If you think an appropriate `TAGS' file already exists for what you
  922. want, but do not know where it is, you can use the `locate' program to
  923. attempt to find it.
  924.  
  925.    Type `M-x locate RET TAGS RET' and Emacs will list for you the full
  926. path names of all your `TAGS' files.  On my system, this command lists
  927. 34 `TAGS' files.  On the other hand, a `plain vanilla' system I
  928. recently installed did not contain any `TAGS' files.
  929.  
  930.    If the tags table you want has been created, you can use the `M-x
  931. visit-tags-table' command to specify it.  Otherwise, you will need to
  932. create the tag table yourself and then use `M-x visit-tags-table'.
  933.  
  934. Building Tags in the Emacs sources
  935. ..................................
  936.  
  937.    The GNU Emacs sources come with a `Makefile' that contains a
  938. sophisticated `etags' command that creates, collects, and merges tags
  939. tables from all over the Emacs sources and puts the information into
  940. one `TAGS' file in the `src/' directory below the top level of your
  941. Emacs source directory.
  942.  
  943.    To build this `TAGS' file, go to the top level of your Emacs source
  944. directory and run the compile command `make tags':
  945.  
  946.      M-x compile RET make tags RET
  947.  
  948. (The `make tags' command works well with the GNU Emacs sources, as well
  949. as with some other source packages.)
  950.  
  951.    For more information, see *Note Tag Tables: (emacs)Tags.
  952.  
  953. 
  954. File: emacs-lisp-intro.info,  Node: Regexp Review,  Next: re-search Exercises,  Prev: etags,  Up: Regexp Search
  955.  
  956. Review
  957. ======
  958.  
  959.    Here is a brief summary of some recently introduced functions.
  960.  
  961. `while'
  962.      Repeatedly evaluate the body of the expression so long as the first
  963.      element of the body tests true.  Then return `nil'.  (The
  964.      expression is evaluated only for its side effects.)
  965.  
  966.      For example:
  967.  
  968.           (let ((foo 2))
  969.             (while (> foo 0)
  970.               (insert (format "foo is %d.\n" foo))
  971.               (setq foo (1- foo))))
  972.           
  973.                =>      foo is 2.
  974.                        foo is 1.
  975.                        nil
  976.  
  977.      (The `insert' function inserts its arguments at point; the
  978.      `format' function returns a string formatted from its arguments
  979.      the way `message' formats its arguments; `\n' produces a new line.)
  980.  
  981. `re-search-forward'
  982.      Search for a pattern, and if the pattern is found, move point to
  983.      rest just after it.
  984.  
  985.      Takes four arguments, like `search-forward':
  986.  
  987.        1. A regular expression that specifies the pattern to search for.
  988.  
  989.        2. Optionally, the limit of the search.
  990.  
  991.        3. Optionally, what to do if the search fails, return `nil' or an
  992.           error message.
  993.  
  994.        4. Optionally, how many times to repeat the search; if negative,
  995.           the search goes backwards.
  996.  
  997. `let*'
  998.      Bind some variables locally to particular values, and then
  999.      evaluate the remaining arguments, returning the value of the last
  1000.      one.  While binding the local variables, use the local values of
  1001.      variables bound earlier, if any.
  1002.  
  1003.      For example:
  1004.  
  1005.           (let* ((foo 7)
  1006.                 (bar (* 3 foo)))
  1007.             (message "`bar' is %d." bar))
  1008.                => `bar' is 21.
  1009.  
  1010. `match-beginning'
  1011.      Return the position of the start of the text found by the last
  1012.      regular expression search.
  1013.  
  1014. `looking-at'
  1015.      Return `t' for true if the text after point matches the argument,
  1016.      which should be a regular expression.
  1017.  
  1018. `eobp'
  1019.      Return `t' for true if point is at the end of the accessible part
  1020.      of a buffer.  The end of the accessible part is the end of the
  1021.      buffer if the buffer is not narrowed; it is the end of the
  1022.      narrowed part if the buffer is narrowed.
  1023.  
  1024. `prog1'
  1025.      Evaluate each argument in sequence and then return the value of the
  1026.      _first_.
  1027.  
  1028.      For example:
  1029.  
  1030.           (prog1 1 2 3 4)
  1031.                => 1
  1032.  
  1033. 
  1034. File: emacs-lisp-intro.info,  Node: re-search Exercises,  Prev: Regexp Review,  Up: Regexp Search
  1035.  
  1036. Exercises with `re-search-forward'
  1037. ==================================
  1038.  
  1039.    * Write a function to search for a regular expression that matches
  1040.      two or more blank lines in sequence.
  1041.  
  1042.    * Write a function to search for duplicated words, such as `the the'.
  1043.      *Note Syntax of Regular Expressions: (emacs)Regexps, for
  1044.      information on how to write a regexp (a regular expression) to
  1045.      match a string that is composed of two identical halves.  You can
  1046.      devise several regexps; some are better than others.  The function
  1047.      I use is described in an appendix, along with several regexps.
  1048.      *Note `the-the' Duplicated Words Function: the-the.
  1049.  
  1050. 
  1051. File: emacs-lisp-intro.info,  Node: Counting Words,  Next: Words in a defun,  Prev: Regexp Search,  Up: Top
  1052.  
  1053. Counting: Repetition and Regexps
  1054. ********************************
  1055.  
  1056.    Repetition and regular expression searches are powerful tools that
  1057. you often use when you write code in Emacs Lisp.  This chapter
  1058. illustrates the use of regular expression searches through the
  1059. construction of word count commands using `while' loops and recursion.
  1060.  
  1061. * Menu:
  1062.  
  1063. * Why Count Words::
  1064. * count-words-region::          Use a regexp, but find a problem.
  1065. * recursive-count-words::       Start with case of no words in region.
  1066. * Counting Exercise::
  1067.  
  1068. 
  1069. File: emacs-lisp-intro.info,  Node: Why Count Words,  Next: count-words-region,  Prev: Counting Words,  Up: Counting Words
  1070.  
  1071. Counting words
  1072. ==============
  1073.  
  1074.    The standard Emacs distribution contains a function for counting the
  1075. number of lines within a region.  However, there is no corresponding
  1076. function for counting words.
  1077.  
  1078.    Certain types of writing ask you to count words.  Thus, if you write
  1079. an essay, you may be limited to 800 words; if you write a novel, you
  1080. may discipline yourself to write 1000 words a day.  It seems odd to me
  1081. that Emacs lacks a word count command.  Perhaps people use Emacs mostly
  1082. for code or types of documentation that do not require word counts; or
  1083. perhaps they restrict themselves to the operating system word count
  1084. command, `wc'.  Alternatively, people may follow the publishers'
  1085. convention and compute a word count by dividing the number of
  1086. characters in a document by five.  In any event, here are commands to
  1087. count words.
  1088.  
  1089. 
  1090. File: emacs-lisp-intro.info,  Node: count-words-region,  Next: recursive-count-words,  Prev: Why Count Words,  Up: Counting Words
  1091.  
  1092. The `count-words-region' Function
  1093. =================================
  1094.  
  1095.    A word count command could count words in a line, paragraph, region,
  1096. or buffer.  What should the command cover?  You could design the
  1097. command to count the number of words in a complete buffer.  However,
  1098. the Emacs tradition encourages flexibility--you may want to count words
  1099. in just a section, rather than all of a buffer.  So it makes more sense
  1100. to design the command to count the number of words in a region.  Once
  1101. you have a `count-words-region' command, you can, if you wish, count
  1102. words in a whole buffer by marking it with `C-x h'
  1103. (`mark-whole-buffer').
  1104.  
  1105.    Clearly, counting words is a repetitive act: starting from the
  1106. beginning of the region, you count the first word, then the second
  1107. word, then the third word, and so on, until you reach the end of the
  1108. region.  This means that word counting is ideally suited to recursion
  1109. or to a `while' loop.
  1110.  
  1111. * Menu:
  1112.  
  1113. * Design count-words-region::   The definition using a `while' loop.
  1114. * Whitespace Bug::              The Whitespace Bug in `count-words-region'.
  1115.  
  1116.